import * as defaults from '../msui-utils/msui-default'
class MsuiFormItemModel {
  constructor({ label = '', value = '', rules = [], template = 'elInput' } = {}) {
    ;(this.label = label),
      (this.value = value),
      (this.rules = rules),
      (this.template = template),
      (this.show = true),
      (this.attrs = {}),
      (this.labelWidth = null)
  }
  type(attrs, type = 'elInput') {
    if (type === 'MsuiSelectBox' && attrs.options instanceof Promise) {
      attrs.options.then((options) => {
        attrs.options = options
      })
    }
    this.attrs = attrs
    this.template = type
    if (this.attrs?.bind?.options && this.attrs.bind.options instanceof Promise) {
      this.attrs.bind.options.then((options) => {
        this.attrs.bind.options = options
      })
      this.attrs.bind.options = []
    }
    return this
  }
  addRules(rules) {
    if (rules instanceof Array) {
      this.rules = rules
    } else if (rules instanceof Object) {
      this.rules.push(rules)
    }
    return this
  }
  getAttrs() {
    return this.attrs
  }
  getSpan() {
    if (this.attrs.bind && this.attrs.bind.span) {
      return Number(this.attrs.bind.span)
    } else {
      return ''
    }
  }
  getFn() {
    if (this.attrs.vOn) {
      this.vOn = this.attrs.vOn
      return this.attrs.vOn
    } else {
      return {}
    }
  }
  getBind() {
    let bind = defaults[this.template] || {}
    bind.placeholder = `请输入${this.label}`
    if (this.attrs.bind) {
      return Object.assign({}, bind, this.attrs.bind)
    } else {
      this.attrs.bind = bind
      return bind
    }
  }
  observe(callBack) {
    //监听value变化进行formater
    Object.defineProperty(this, 'value', {
      set: (val) => {
        if (val === this.value) return
        this.value = callBack(val)
      }
    })
    return this
  }
  setShow(boolean) {
    this.show = boolean
    return this
  }
  render() {
    return this.template
  }
  setValue(value) {
    this.value = value
    return this
  }
  getValue() {
    return this.value
  }
  setStyle(style) {
    this.style = style
    return this
  }
  setLabelWidth(width) {
    this.labelWidth = width
    return this
  }
}

export default MsuiFormItemModel
